package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@Order(0) // 值越小越优先执行
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");//小刀
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //是否属于白名单
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        for (String url : urlList) {
            if (path.contains(url)){
                return chain.filter(exchange);
            }
        }

        //拦截认证

        String token = request.getHeaders().getFirst("token");

        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//终止
        }

        //解析token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);

        int i = AppJwtUtil.verifyToken(claimsBody);

        if (i <1){
            Object id = claimsBody.get("id");
            log.info("网关认证成功 id为： {}" , id);

            request.mutate().header("userId",String.valueOf(id));

            exchange.mutate().request(request);//修改exchange对象

            return chain.filter(exchange);//放行

        }

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();//终止
    }
}
